package com.wiselink.naver.productcatalog;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.wiselink.exception.NaverException;
import com.wiselink.naver.productcatalog.response.*;
import com.wiselink.common.utils.CollectionUtils;
import com.wiselink.common.utils.StringUtils;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class NaverApiUtils {
    private static final Logger log = LoggerFactory.getLogger(NaverApiUtils.class);

    /**
     * 获取产品品牌列表
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EB%B8%8C%EB%9E%9C%EB%93%9C/operation/getBrandList.product">...</a>
     *
     * @param accessToken accessToken
     * @param name        品牌名称
     * @return List<Object>
     */
    public static List<ProductBrand> getProductBrands(String accessToken, String name) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/product-brands?name=" + name, "getProductBrands");
        return JSONArray.parseArray(bodyStr, ProductBrand.class);
    }

    /**
     * 获取所有产品尺寸和类型集合
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%82%AC%EC%9D%B4%EC%A6%88/operation/getSizeTypeVoList.product">...</a>
     *
     * @param accessToken accessToken
     * @return List<ProductSize>
     */
    public static List<ProductSize> getProductSizes(String accessToken) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/product-sizes", "getProductSizes");
        return JSONArray.parseArray(bodyStr, ProductSize.class);
    }

    /**
     * 获取指定产品尺码
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%82%AC%EC%9D%B4%EC%A6%88/operation/getSizeTypeVo.product">...</a>
     *
     * @param accessToken accessToken
     * @param sizeTypeId  sizeTypeId
     * @return ProductSize
     */
    public static ProductSize getProductSize(String accessToken, String sizeTypeId) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/product-sizes/" + sizeTypeId, "getProductSizeBySizeTypeId");
        return JSONObject.parseObject(bodyStr, ProductSize.class);
    }

    /**
     * 获取整个属性值单位列表
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%83%81%ED%92%88-%EC%86%8D%EC%84%B1/operation/getAttributeValueUnitList.product">...</a>
     *
     * @param accessToken accessToken
     * @return List<ProductAttributeValueUnit>
     */
    public static List<ProductAttributeValueUnit> getProductAttributeValueUnits(String accessToken) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/product-attributes/attribute-value-units", "getProductAttributeValueUnits");
        return JSONArray.parseArray(bodyStr, ProductAttributeValueUnit.class);
    }

    /**
     * 按类别搜索属性值列表
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%83%81%ED%92%88-%EC%86%8D%EC%84%B1/operation/getAttributeValueList.product">...</a>
     *
     * @param accessToken accessToken
     * @param categoryId  categoryId
     * @return List<ProductAttributeValue>
     */
    public static List<ProductAttributeValue> getProductAttributeValues(String accessToken, String categoryId) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/product-attributes/attribute-values?categoryId=" + categoryId, "getProductAttributeValues");
        return JSONArray.parseArray(bodyStr, ProductAttributeValue.class);
    }

    /**
     * 按类别查询属性列表
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%83%81%ED%92%88-%EC%86%8D%EC%84%B1/operation/getAttributeList.product">...</a>
     *
     * @param accessToken accessToken
     * @param categoryId  categoryId
     * @return List<ProductAttribute>
     */
    public static List<ProductAttribute> getProductAttributes(String accessToken, String categoryId) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/product-attributes/attributes?categoryId=" + categoryId, "getProductAttributes");
        return JSONArray.parseArray(bodyStr, ProductAttribute.class);
    }

    /**
     * 条件查询原产国代码列表
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%83%81%ED%92%88-%EC%9B%90%EC%82%B0%EC%A7%80-%EC%A0%95%EB%B3%B4/operation/getAllOriginAreaList.product">...</a>
     *
     * @param accessToken accessToken
     * @param code        代码
     * @param name        名称
     * @return List<ProductOriginArea>
     */
    public static List<ProductOriginArea> getProductOriginAreas(String accessToken, String code, String name) {
        String qs = "";
        List<String> qsList = new ArrayList<>(2);
        if (StringUtils.isNotEmpty(code)) {
            qsList.add("code=" + code);
        }
        if (StringUtils.isNotEmpty(name)) {
            qsList.add("name=" + name);
        }
        if (!qsList.isEmpty()) {
            qs = "/query?" + String.join("&", qsList);
        }
        String bodyStr = get(
                accessToken,
                "https://api.commerce.naver.com/external/v1/product-origin-areas" + qs,
                "getProductOriginAreas");
        JSONObject jsonObject = JSONObject.parse(bodyStr);
        if (Objects.nonNull(jsonObject)) {
            JSONArray jsonArray = jsonObject.getJSONArray("originAreaCodeNames");
            return jsonArray.toJavaList(ProductOriginArea.class);
        }
        return new ArrayList<>();
    }

    /**
     * 查询子原产地列表
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%83%81%ED%92%88-%EC%9B%90%EC%82%B0%EC%A7%80-%EC%A0%95%EB%B3%B4/operation/getSubOriginAreaList.product">...</a>
     *
     * @param accessToken accessToken
     * @param code        code
     * @return List<ProductOriginArea>
     */
    public static List<ProductOriginArea> getSubOriginAreas(String accessToken, String code) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/product-origin-areas/sub-origin-areas?code=" + code, "getSubOriginAreas");
        JSONObject jsonObject = JSONObject.parse(bodyStr);
        if (Objects.nonNull(jsonObject)) {
            JSONArray jsonArray = jsonObject.getJSONArray("subOriginAreaCodeNames");
            return jsonArray.toJavaList(ProductOriginArea.class);
        }
        return new ArrayList<>();
    }

    /**
     * 注册多个产品图片
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%83%81%ED%92%88-%EC%9D%B4%EB%AF%B8%EC%A7%80/operation/upload.product">...</a>
     *
     * @param accessToken accessToken
     * @param imageFiles  imageFiles 最多可注册10个。可上传图片的格式为JPG、GIF、PNG、BMP。최대 10개까지 등록 가능. 업로드할 수 있는 이미지의 형식은 JPG, GIF, PNG, BMP입니다.
     * @return List<String> 图片地址
     */
    public static List<ProductImage> registerProductImages(String accessToken, List<String> imageFiles) {
        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (String imageFile : imageFiles) {
            File file = new File(imageFile);
            RequestBody fileBody = RequestBody.create(MediaType.parse(getMimeType(file)), file);
            multipartBuilder.addFormDataPart("imageFiles", file.getName(), fileBody);
        }
        MultipartBody body = multipartBuilder.build();
        Request request = new Request.Builder()
                .url("https://api.commerce.naver.com/external/v1/product-images/upload")
                .post(body)
                .addHeader("Authorization", accessToken)
                .addHeader("content-type", "multipart/form-data")
                .build();
        String bodyStr = execute(request, "registerProductImages");
        JSONObject jsonObject = JSONObject.parse(bodyStr);
        return JSONArray.parseArray(jsonObject.getString("images"), ProductImage.class);
    }

    /**
     * 产品信息提供公告 产品组列表查询
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%83%81%ED%92%88%EC%A0%95%EB%B3%B4%EC%A0%9C%EA%B3%B5%EA%B3%A0%EC%8B%9C/operation/getAllProductInfoProvidedNoticeTypeVo.product">...</a>
     *
     * @param accessToken accessToken
     * @param categoryId  类别 ID
     * @return List<ProductForProvidedNotice> 产品信息提供公告 产品组列表
     */
    public static List<ProductForProvidedNotice> getProductForProvidedNotices(String accessToken, String categoryId) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/products-for-provided-notice?categoryId=" + categoryId, "getProductsForProvidedNotice");
        return JSONArray.parseArray(bodyStr, ProductForProvidedNotice.class);
    }

    /**
     * 产品信息提供公告 产品组单项搜索
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%83%81%ED%92%88%EC%A0%95%EB%B3%B4%EC%A0%9C%EA%B3%B5%EA%B3%A0%EC%8B%9C/operation/getProductInfoProvidedNoticeTypeVo.product">...</a>
     *
     * @param accessToken                   accessToken
     * @param productInfoProvidedNoticeType 产品信息提供的通知类型
     * @return ProductForProvidedNotice 产品信息提供公告
     */
    public static ProductForProvidedNotice getProductForProvidedNotice(String accessToken, String productInfoProvidedNoticeType) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/products-for-provided-notice/" + productInfoProvidedNoticeType, "getProductsForProvidedNotice");
        return JSONObject.parseObject(bodyStr, ProductForProvidedNotice.class);
    }

    /**
     * 按类别搜索标准选项
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%98%B5%EC%85%98/operation/getStandardOptionByCategory.product">...</a>
     *
     * @param accessToken accessToken
     * @param categoryId  categoryId
     * @return StandardOption
     */
    public static StandardOption getStandardOption(String accessToken, String categoryId) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/options/standard-options?categoryId=" + categoryId, "getStandardOptions");
        return JSONObject.parseObject(bodyStr, StandardOption.class);
    }

    /**
     * 根据名字查询生产厂商列表
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%A0%9C%EC%A1%B0%EC%82%AC/operation/getManufacturerList.product">...</a>
     *
     * @param accessToken accessToken
     * @param name        生产厂商名字
     * @return List<ProductManufacturer>
     */
    public static List<ProductManufacturer> getProductManufacturers(String accessToken, String name) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/product-manufacturers?name=" + name, "getProductManufacturers");
        return JSONArray.parseArray(bodyStr, ProductManufacturer.class);
    }

    /**
     * 目录查询
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%B9%B4%ED%83%88%EB%A1%9C%EA%B7%B8">...</a>
     *
     * @param accessToken accessToken
     * @param name        要搜索的目录名称 必填项
     * @param page        页码 选填项 默认值为1
     * @param size        页面大小 选填项 默认值为100
     * @return ProductModelResponse
     */
    public static ProductModelResponse getProductModels(String accessToken, String name, Integer page, Integer size) {
        String qs = "";
        if (page != null) {
            qs += "&page=" + page;
        }
        if (size != null) {
            qs += "&size=" + size;
        }
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/product-models?name=" + name + qs, "getProductModels");
        return JSONObject.parseObject(bodyStr, ProductModelResponse.class);
    }

    /**
     * 目录查询
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%B9%B4%ED%83%88%EB%A1%9C%EA%B7%B8/operation/getModel.product">...</a>
     *
     * @param accessToken accessToken
     * @param id          要搜索的目录id 必填
     * @return ProductModelResponse.Content
     */
    public static ProductModelResponse.Content getProductModelById(String accessToken, Long id) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/product-models/" + id, "getProductModelById");
        return JSONObject.parseObject(bodyStr, ProductModelResponse.Content.class);
    }

    /**
     * 查询所有类别
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%B9%B4%ED%85%8C%EA%B3%A0%EB%A6%AC/operation/getCategoryList.product">...</a>
     *
     * @param accessToken accessToken
     * @param last        是否只查看叶子类别 默认值为false
     * @return List<Category>
     */
    public static List<Category> getCategories(String accessToken, Boolean last) {
        String qs = "";
        if (last != null) {
            qs += "?last=" + last;
        }
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/categories" + qs, "getCategories");
        return JSONArray.parseArray(bodyStr, Category.class);
    }

    /**
     * 根据类别ID查询类别
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%B9%B4%ED%85%8C%EA%B3%A0%EB%A6%AC/operation/getCategory.product">...</a>
     *
     * @param accessToken accessToken
     * @param categoryId  类别ID 必填
     * @return Category
     */
    public static Category getCategoryById(String accessToken, String categoryId) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/categories/" + categoryId, "getCategoryById");
        return JSONObject.parseObject(bodyStr, Category.class);
    }

    /**
     * 根据类别ID查询子类别
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%EC%B9%B4%ED%85%8C%EA%B3%A0%EB%A6%AC/operation/getSubCategory.product">...</a>
     *
     * @param accessToken accessToken
     * @param categoryId  类别ID 必填
     * @return List<Category>
     */
    public static List<Category> getSubCategories(String accessToken, String categoryId) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/categories/" + categoryId + "/sub-categories", "getSubCategories");
        return JSONArray.parseArray(bodyStr, Category.class);
    }

    /**
     * 查询推荐标签列表
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%ED%83%9C%EA%B7%B8/operation/getRecommendTags.product">...</a>
     *
     * @param accessToken accessToken
     * @param keyword     搜索关键字 必填
     * @return List<Tag>
     */
    public static List<Tag> getTags(String accessToken, String keyword) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v2/tags/recommend-tags?keyword=" + keyword, "getTags");
        return JSONArray.parseArray(bodyStr, Tag.class);
    }

    /**
     * 根据标签查询是否存在限制标签列表
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%ED%83%9C%EA%B7%B8/operation/isRestrictTags.product">...</a>
     *
     * @param accessToken accessToken
     * @param tags        标签字符串数组 必填
     * @return List<RestrictedTag>
     */
    public static List<RestrictedTag> getRestrictedTags(String accessToken, String[] tags) {
        // 取出tags中的元素，用逗号分隔，拼成一个字符串
        String tagsStr = String.join(",", tags);
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v2/tags/restricted-tags?tags=" + tagsStr, "getRestrictedTags");
        return JSONArray.parseArray(bodyStr, RestrictedTag.class);
    }

    /**
     * 根据类别id查询销售选项信息
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%ED%83%9C%EA%B7%B8/operation/isRestrictTags.product">...</a>
     *
     * @param accessToken accessToken
     * @param categoryId  类别ID 必填
     * @return StandardPurchaseOptionGuide
     */
    public static StandardPurchaseOptionGuide getStandardPurchaseOptionGuide(String accessToken, String categoryId) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v2/standard-purchase-option-guides?categoryId=" + categoryId, "getStandardPurchaseOptionGuide");
        return JSONObject.parseObject(bodyStr, StandardPurchaseOptionGuide.class);
    }

    /**
     * 获取naver卖家的物流公司列表
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%ED%8C%90%EB%A7%A4%EC%9E%90-%EB%AC%BC%EB%A5%98/operation/getLogisticsCompanies.nfa">...</a>
     *
     * @param accessToken accessToken
     * @return List<LogisticsCompanies> 物流公司列表
     */
    public static List<LogisticsCompany> getLogisticsCompanies(String accessToken) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/logistics/logistics-companies", "getLogisticsCompanies");
        JSONObject object = JSONObject.parseObject(bodyStr);
        if (Objects.nonNull(object)) {
            JSONArray logisticsCompanies = object.getJSONArray("logisticsCompanies");
            return logisticsCompanies.toJavaList(LogisticsCompany.class);
        }
        return new ArrayList<>();
    }

    /**
     * 获取naver卖家的仓库信息
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%ED%8C%90%EB%A7%A4%EC%9E%90-%EB%AC%BC%EB%A5%98/operation/getOutboundLocations.nfa">...</a>
     *
     * @param accessToken accessToken
     * @return List<OutboundLocation> 卖家的仓库信息列表
     */
    public static List<OutboundLocation> getOutboundLocations(String accessToken) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/logistics/outbound-locations", "getOutboundLocations");
        return JSONArray.parseArray(bodyStr, OutboundLocation.class);
    }

    /**
     * 条件查询合并配送组列表
     *
     * @param accessToken accessToken
     * @param name        合并发货组名称 LIKE 搜索" 捆绑发货组名称%
     * @param baseGroup   默认分组与否
     * @param usable      是否启用
     * @param page        页码 默认值为1
     * @param size        页面大小 默认值为50 每页最多可以查询100
     * @return BundleGroupResponse
     */
    public static BundleGroupResponse searchBundleGroups(String accessToken, String name, Boolean baseGroup, Boolean usable, Integer page, Integer size) {
        List<String> qsList = new ArrayList<>();
        String qs = "";
        if (StringUtils.isNotEmpty(name)) {
            qsList.add("name=" + name);
        }
        if (Objects.nonNull(baseGroup)) {
            qsList.add("baseGroup=" + baseGroup);
        }
        if (Objects.nonNull(usable)) {
            qsList.add("usable=" + usable);
        }
        if (Objects.nonNull(page)) {
            qsList.add("page=" + page);
        }
        if (Objects.nonNull(size)) {
            qsList.add("size=" + size);
        }
        if (!CollectionUtils.isEmpty(qsList)) {
            qs = "?" + StringUtils.join(qsList, "&");
        }
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/product-delivery-info/bundle-groups" + qs, "searchBundleGroups");
        return JSONObject.parseObject(bodyStr, BundleGroupResponse.class);
    }

    /**
     * 根据id查询合并配送组
     *
     * @param accessToken           accessToken
     * @param deliveryBundleGroupId 合并配送组id
     * @return BundleGroupResponse.DeliveryBundleGroup
     */
    public static BundleGroupResponse.DeliveryBundleGroup getBundleGroupById(String accessToken, Long deliveryBundleGroupId) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/product-delivery-info/bundle-groups/" + deliveryBundleGroupId, "getBundleGroupById");
        JSONObject object = JSONObject.parseObject(bodyStr);
        return object.getObject("deliveryBundleGroup", BundleGroupResponse.DeliveryBundleGroup.class);
    }

    /**
     * 获取退货物流公司列表
     *
     * @param accessToken accessToken
     * @return List<ReturnDeliveryCompany>
     */
    public static List<ReturnDeliveryCompany> getReturnDeliveryCompanies(String accessToken) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v2/product-delivery-info/return-delivery-companies", "getReturnDeliveryCompanies");
        JSONObject jsonObject = JSONObject.parseObject(bodyStr);
        if (Objects.nonNull(jsonObject)) {
            JSONArray jsonArray = jsonObject.getJSONArray("returnDeliveryCompanies");
            return jsonArray.toJavaList(ReturnDeliveryCompany.class);
        }
        return new ArrayList<>();
    }

    /**
     * 获取卖家的地址列表
     * <a href="https://apicenter.commerce.naver.com/ko/basic/commerce-api#tag/%ED%8C%90%EB%A7%A4%EC%9E%90-%EC%A3%BC%EC%86%8C%EB%A1%9D/operation/getPageAddresses.sellers">...</a>
     *
     * @param accessToken accessToken
     * @param page        page
     * @return AddressBookResponse
     */
    public static AddressBookResponse getAddressBooks(String accessToken, Integer page) {
        String bodyStr = get(accessToken, "https://api.commerce.naver.com/external/v1/seller/addressbooks-for-page?page=" + page, "getAddressBooks");
        return JSONObject.parseObject(bodyStr, AddressBookResponse.class);
    }

    /**
     * get请求
     *
     * @param accessToken accessToken
     * @param url         url
     * @param mark        标记
     * @return 响应体字符串
     */
    private static String get(String accessToken, String url, String mark) {
        Request request = new Request.Builder().url(url).get().addHeader("Authorization", accessToken).build();
        return execute(request, mark);
    }

    /**
     * 执行请求
     *
     * @param request request
     * @param mark    mark
     * @return 响应体字符串
     */
    private static String execute(Request request, String mark) {
        OkHttpClient client = new OkHttpClient();
        try (Response response = client.newCall(request).execute()) {
            int code = response.code();
            log.info("code: {}", code);
            String body = null;
            if (response.body() != null) {
                body = response.body().string();
            }
            log.error("Response.body: {}", body);
            if (code == 200) {
                return body;
            }
            String errMsg = null;
            try {
                JSONObject object = JSONObject.parseObject(body);
                if (Objects.nonNull(object)) {
                    errMsg = object.getString("message");
                    if (object.containsKey("invalidInputs")) {
                        errMsg += "; invalidInputs: " + object.getString("invalidInputs");
                    }
                    log.error("code: {}, message: {}", object.getString("code"), errMsg);
                }
            } catch (Exception ignored) {
            }
            throw new NaverException(mark + " fail, reason: " + errMsg);
        } catch (IOException e) {
            log.error("{} error", mark, e);
            throw new NaverException(mark + " error");
        }
    }

    /**
     * 获取文件类型 只兼容：JPG、GIF、PNG、BMP类型
     *
     * @param file file
     * @return 文件类型
     */
    private static String getMimeType(File file) {
        String extension = getFileExtension(file);
        if ("jpg".equalsIgnoreCase(extension) || "jpeg".equalsIgnoreCase(extension)) {
            return "image/jpeg";
        } else if ("gif".equalsIgnoreCase(extension)) {
            return "image/gif";
        } else if ("png".equalsIgnoreCase(extension)) {
            return "image/png";
        } else if ("bmp".equalsIgnoreCase(extension)) {
            return "image/bmp";
        } else {
            throw new IllegalArgumentException("Unsupported image format: " + extension);
        }
    }

    private static String getFileExtension(File file) {
        String name = file.getName();
        int lastIndexOf = name.lastIndexOf(".");
        if (lastIndexOf == -1) {
            return ""; // no extension
        }
        return name.substring(lastIndexOf + 1).toLowerCase();
    }

}
